package com.ict.interceptor;

import com.ict.util.RSAUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.security.PrivateKey;

/**
 * restTemplate加签拦截器
 */
@Component
public class SignatureInterceptor implements ClientHttpRequestInterceptor {

    private final PrivateKey privateKey; // 客户端的私钥

    public SignatureInterceptor(PrivateKey privateKey) {
        this.privateKey = privateKey;
    }

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
            throws IOException {
        // 只使用URI的路径部分进行签名
        String uriPath = request.getURI().getPath();

        // 生成nonceId和时间戳
        String nonceId = RSAUtil.generateNonceId();
        long timestamp = RSAUtil.generateTimestamp();

        // 构建签名数据
        String data = uriPath + nonceId + timestamp; // 可以包含更多数据，如请求体

        // 生成签名
        String signature = null;
        try {
            signature = RSAUtil.sign(data, privateKey);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // 将签名、nonceId、时间戳放入请求头
        HttpHeaders headers = request.getHeaders();
        headers.add("Signature", signature);
        headers.add("NonceId", nonceId);
        headers.add("Timestamp", String.valueOf(timestamp));

        // 继续执行请求
        return execution.execute(request, body);
    }
}
